package com.dy.system.aop;

import com.dy.basic.util.IPAddressUtils;
import com.dy.system.domain.Logs;
import com.dy.system.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;

@Component
@Aspect
@Slf4j
public class LogAop {

    @Autowired
    private LogService logService;


    @Around("@annotation(com.dy.system.anno.LogAnno)")
    public Object logAop(ProceedingJoinPoint pjp) throws Throwable {
        // 获取请求信息
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 获取请求用户IP
        String userIP = IPAddressUtils.getIpAdrress(request);
        System.out.println(userIP);
        // 获取id
        Object[] args = pjp.getArgs();
        String s = Arrays.toString(args);
        System.out.println(s);
        String[] split = s.split(",");
        String id = split[0].substring(12);
        String name1 = split[1].substring(6);
        System.out.println("id = " + id);
        String des3="";
        String des4="";
        if (id.equals("null")){
            des3 = "这是一个添加的方法";
            des4 = "insert";
            System.out.println(des3);
            System.out.println(des4);
        } else {
            des3 = "这是一个修改的方法...";
            des4 = "update";
            System.out.println(des3);
            System.out.println(des4);
        }
        System.out.println(s);
        System.out.println(id);
        Date date1 = new Date();

        // 执行方法
        Object proceed = pjp.proceed();
        Logs logs = new Logs();
        logs.setName(des3);
        logs.setCode(des4);
        Date date2 = new Date();
        logs.setCreateDate(new Date());
        logs.setIp(userIP);
        logService.insert(logs);

        return  proceed;
    }
}
